import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { UserService } from './user/user.service';
import { Authority } from '@prisma/client';
import { Reflector } from '@nestjs/core';


@Injectable()
export class PermissionGuard implements CanActivate {

  @Inject(UserService)
  private userService: UserService;

  @Inject()
  private reflector: Reflector;

  async canActivate(
    context: ExecutionContext,
  ): Promise<boolean> {
    const request: Request = context.switchToHttp().getRequest();

    if (!request.user) {
      return true;
    }
    const arr = []
    arr.push(request.user.roles)

    const roles = await this.userService.findRolesByIds(arr.map(item => item.id))

    const permissions: Authority[] = roles.reduce((total, current) => {
      total.push(...current.RoleAuthority.map(item => item.Authority));
      return total;
    }, []);

    console.log(permissions);

    const requiredPermissions = this.reflector.getAllAndOverride<string[]>('require-permission', [
      context.getClass(),
      context.getHandler()
    ]) || [];

    console.log(requiredPermissions);

    for (let i = 0; i < requiredPermissions?.length; i++) {
      const curPermission = requiredPermissions[i];
      const found = permissions.find(item => item.name === curPermission);
      if (!found) {
        throw new UnauthorizedException('您没有访问该接口的权限');
      }
    }


    return true;
  }
}
